# -*- coding: utf-8 -*-
from MyTgSpi import *
import tgateapi as api
import configparser
import threading
import os
import time

#local config check check
if(os.path.exists("config.local.ini")):
	configfile = "config.local.ini"
else:
	configfile = "config.ini"


configins=configparser.ConfigParser()
configins.read(configfile)
#Addr
FrontAddr=configins['network']['tgatefront']
#BaseInfo
BROKERID=configins['baseinfo']['brokerid']
USERID=configins['baseinfo']['userid']
#search conf
TIMEOUTSEC=int(configins['searchopt']['timeoutsec'])
#tgateqry conf
APPID=configins['tgateqry']['appid']

#DataTitle
ReqTgateInfoTitle = ["BrokerID", "UserID", "Address", "DRIdentityID", "DRIdentityName", "AddrSrvMode", "AddrVer", "AddrNo", "AddrName", "IsSM", "IsLocalAddr", "Remark", "Site", "NetOperator"]

#decorator
def run_time(func):
	def wrap(argv1):
		start_time = time.time()
		rt = func(argv1)
		end_time = time.time()
		print('used time:', (end_time - start_time) * 1000, 'ms')
		return rt
	return wrap

class CTgateApi(api.CTGateFtdcApi):
	def __init__(self):
		self.tspi=''
		self.tapi=''
		self.ctlevent=threading.Event()
		#query return
		self.ReqTgateInfoData=[]

	@run_time
	def start(self):
		self.tapi=api.CTGateFtdcApi.CreateTGateFtdcApi()
		self.tspi=CTgateSpi(self)
		self.tapi.RegisterTGAddr(FrontAddr)
		self.tapi.RegisterSpi(self.tspi)


	@run_time
	def ReqTgateInfo(self):
		self.ReqTgateInfoData.clear()
		self.ReqTgateInfoData.append(ReqTgateInfoTitle)
		qryfield = api.CTGateFtdcQryTGIpAddrParamField()
		qryfield.BrokerID = BROKERID
		qryfield.UserID = USERID
		qryfield.AppID = APPID
		self.tapi.ReqQryTGIpAddrParam(qryfield,0)
		PrintSendName("ReqQryTGIpAddrParam")
		self.ctlevent.wait(timeout = TIMEOUTSEC)
		if(self.ctlevent.isSet() == True):
			self.ctlevent.clear()
			StringPrint(self.ReqTgateInfoData)
			return self.ReqTgateInfoData
		else:
			return 233



#print func name
def PrintSendName(sendname):
	sendmsg = "send " + sendname + " ok"
	print(sendmsg)

def ListPrint(datalist):
	for currlist in datalist:
		DealTooMax(currlist)
		listlen = len(currlist)
		formatlist = tuple(currlist)
		print("|%-25s|" * listlen % formatlist)

def StringPrint(datalist):
	for currlist in datalist:
		print("*" * 50)
		print(currlist)
		print("*" * 50)

def SettleinfoWrite(datalist, filename):
	settlefh = open(filename, mode="w")
	for currlist in datalist:
		print(currlist[1], file=settlefh)
	settlefh.close()